package com.itheima.interceptor;

import com.itheima.util.CurrentHolder;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();//获取路径

        if (url.contains("/login")){
            log.info("登录请求，直接放行");
            return true;
        }

        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            log.info("获取到的JWT令牌为空，返回错误的结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJwt(jwt);
//            Integer empId = Integer.valueOf(claims.get("id").toString());
//            CurrentHolder.setCurrentId(empId);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回错误结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        log.info("令牌合法， 放行");
        return true;

//        //清空当前线程绑定的id
//        CurrentHolder.remove();


    }
}
